﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Collections.Specialized;
using Ylh.DAL;

namespace Ylh.Data
{
  public  class RefInSert
    {

        public static bool InserObjedct(Type T, Object O, List<String> IExcept, String ConStr)
        {
            TableAttribute tableattribute = new TableAttribute();
            ColumnAttribute[] columnattribute;
            EntityBasePub.GetEntityProperty(T, out tableattribute, out columnattribute);
            NameValueCollection value = EntityBasePub.GetPropertyValue(O);
            String StrSeek = String.Empty;
            String StrValue = String.Empty;
            foreach (ColumnAttribute col in columnattribute)
            {
                if (IExcept != null && IExcept.Contains(col.ColumnName)) continue;
                if (col.Identity) continue;
                StrSeek += col.ColumnName + ",";
                StrValue += "@" + col.ColumnName + ",";
            }
            String StrCmd = @" INSERT INTO " + tableattribute.TableName + "(" + StrSeek.TrimEnd(',') + ") VALUES" + "(" + StrValue.TrimEnd(',') + ")";
            return DbFactory.CreateInstance().CreateDb().ExecuteNonQuery(StrCmd, CommandType.Text, value, ConStr) > 0;
        }

        public static bool InsertDatatable(Type T, DataTable dt, String ConStr)
        {
            TableAttribute tableattribute = new TableAttribute();
            ColumnAttribute[] columnattribute;
            EntityBasePub.GetEntityProperty(T, out tableattribute, out columnattribute);

            String SelectColumn = String.Empty;
            List<string> IExcept = new List<string>();
            foreach (ColumnAttribute Col in columnattribute)
            {
                SelectColumn += Col.ColumnName + ",";
                //不插入自增键
                if (Col.Identity) IExcept.Add(Col.ColumnName);
            }
            String StrSelectCmd = @"SELECT TOP 0 " + SelectColumn.TrimEnd(',') + " FROM " + tableattribute.TableName;

            return DbFactory.CreateInstance().CreateDb().InsertDataTable(StrSelectCmd, dt, tableattribute.TableName, IExcept, ConStr) > 0;
        }

  }
}
